package com.luckku.boot.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.luckku.boot.common.api.ApiResult;
import com.luckku.boot.model.entity.*;
import com.luckku.boot.model.vo.CartInfoVo;
import com.luckku.boot.model.vo.CartVo;
import com.luckku.boot.model.vo.OrderVo;
import com.luckku.boot.service.*;
import com.luckku.boot.utils.SnowFlakeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author luckku
 * @date 2021/12/18
 */

@Controller
@RequestMapping("/order")
public class OrderController {

    @Autowired
    IOrderService orderService;
    @Autowired
    IOrderGoodsService orderGoodsService;
    @Autowired
    IGoodsService goodsService;
    @Autowired
    ICartService cartService;
    @Autowired
    ICouponService couponService;
    @Autowired
    ICouponUserService couponUserService;
    @Autowired
    IUserService userService;
    @Autowired
    SnowFlakeUtil snowFlakeUtil;


    /**
     * /order/getOrderList
     * 查询所有订单
     */
    @ResponseBody
    @GetMapping("/getOrderList")
    public ApiResult<List<OrderVo>> getOrderList() {
        List<OrderVo> orderVoList = new ArrayList<>();
        List<OrderInfo> orderInfoList = orderService.list(
                new QueryWrapper<OrderInfo>().orderByDesc("create_time")
        );
        for (OrderInfo orderInfo : orderInfoList) {
            String orderId = orderInfo.getOrderId();
            OrderVo orderVo = OrderVo.builder().orderId(orderId)
                    .storeId(orderInfo.getStoreId())
                    .orderState(orderInfo.getOrderState())
                    .usePoint(orderInfo.getUsePoint())
                    .orderCost(orderInfo.getOrderCost())
                    .discount(orderInfo.getDiscount())
                    .getPoint(orderInfo.getGetPoint())
                    .aliTradeNum(orderInfo.getAliTradeNum())
                    .payMethod(orderInfo.getPayMethod())
                    .createTime(orderInfo.getCreateTime())
                    .payTime(orderInfo.getPayTime())
                    .build();
            List<CartVo> cartVoList = orderService.getOrderGoodsList(orderId,orderInfo.getStoreId());
            for (CartVo cartVo : cartVoList) {
                OrderGoods goods = orderGoodsService.getOne(
                        new QueryWrapper<OrderGoods>().eq("order_id", orderId)
                                .eq("goods_id", cartVo.getGoodsId())
                );
                cartVo.setCount(goods.getCount());
            }
            orderVo.setCartList(cartVoList);
            orderVoList.add(orderVo);
        }
        return ApiResult.success(orderVoList);
    }

    /**
     * /order/pointRedeem
     * 积分兑换生成订单
     */
    @ResponseBody
    @PostMapping("/pointRedeem")
    public ApiResult<OrderInfo> redeemGoods(@RequestParam("userId") String userId, @RequestParam("goodsId") String goodsId) {
        Long price = goodsService.getPriceById(goodsId);
        String orderId = String.valueOf(snowFlakeUtil.snowflakeId());
        OrderInfo orderInfo = OrderInfo.builder()
                .orderId(orderId)
                .userId(userId)
                .orderState("1")
                .usePoint(1L)
                .createTime(new Date())
                .payTime(new Date())
                .orderCost(price)
                .discount(0L)
                .build();
        orderService.save(orderInfo);
        orderGoodsService.save(
                OrderGoods.builder().orderId(orderId)
                        .goodsId(goodsId).count(1L).build()
        );
        User user = userService.getById(userId);
        user.setPoint(user.getPoint()-price);
        userService.updateById(user);
        return ApiResult.success();
    }

    /**
     * /order/generateOrder
     * 购物车生成订单
     */
    @ResponseBody
    @PostMapping("/generateOrder")
    public ApiResult<OrderInfo> generateOrder(@RequestParam("userId") String userId, @RequestParam("storeId") String storeId, @Nullable @RequestParam("couponId") String couponId) {
        CartInfoVo cartInfoVO = cartService.getUserCart(userId, storeId);
        String orderId = String.valueOf(snowFlakeUtil.snowflakeId());
        Long discount = 0L;
        Coupon coupon = couponService.getById(couponId);
        if (coupon != null) {
            discount = coupon.getDiscount();
            CouponUser couponUser = couponUserService.getOne(
                    new QueryWrapper<CouponUser>().eq("user_id", userId)
                            .eq("coupon_id", couponId)
            );
            Long count = couponUser.getCount();
            if (count>1){
                couponUserService.updateById(couponUser.setCount(count-1));
            }
            else {
                couponUserService.remove(
                        new QueryWrapper<CouponUser>().eq("user_id", userId)
                                .eq("coupon_id", couponId)
                );
            }
        }
        OrderInfo orderInfo = OrderInfo.builder().orderId(orderId).userId(userId).storeId(storeId)
                .orderCost(cartInfoVO.getTotalPrice().longValue())
                .orderState("0").discount(discount).usePoint(0L)
                .createTime(new Date())
                .build();
        orderService.save(orderInfo);
        for (CartVo cartVO : cartInfoVO.getCartVoList()) {
            OrderGoods orderGoods = OrderGoods.builder().orderId(orderId)
                    .goodsId(cartVO.getGoodsId())
                    .count(cartVO.getCount())
                    .build();
            orderGoodsService.save(orderGoods);
        }
        return ApiResult.success(orderInfo);
    }

    /**
     * /order/callback
     * 监听回调
     */
    @ResponseBody
    @PostMapping("/callback")
    public ApiResult<OrderInfo> listenerCallback(@RequestParam("userId") String userId, @RequestParam("orderId") String orderId) {
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("order_id", orderId);
        int count = orderService.count(queryWrapper);
        return count > 0 ? ApiResult.success() : ApiResult.failed();
    }

    /**
     * /order/getCashFlow
     * 获取近n+1日现金流
     */
    @ResponseBody
    @GetMapping("/getCashFlow")
    public ApiResult<Long> getCashFlow(@RequestParam("days") Long days) {
        Long cashFlow = orderService.getCashFlow(days);
        return  ApiResult.success(cashFlow);
    }
    /**
     * /order/getStoreCashFlow
     * 获取近n+1日现金流（限定店铺）
     */
    @ResponseBody
    @GetMapping("/getStoreCashFlow")
    public ApiResult<Long> getStoreCashFlow(@RequestParam("days") Long days, @RequestParam("storeId") String storeId) {
        Long storeCashFlow = orderService.getStoreCashFlow(days, storeId);
        return  ApiResult.success(storeCashFlow);
    }

    /**
     * /order/getBestSelling
     * 获取销量最佳单品
     */
    @ResponseBody
    @GetMapping("/getBestSelling")
    public ApiResult<Goods> getBestSelling() {
        Goods beseSelling = orderService.getBestSelling();
        return ApiResult.success(beseSelling);
    }
    /**
     * /order/getBestSellingCount
     * 获取销量最佳单品
     */
    @ResponseBody
    @GetMapping("/getBestSellingCount")
    public ApiResult<Long> getBestSellingCount() {
        Long count = orderService.getBestSellingCount();
        return ApiResult.success(count);
    }

    /**
     * /order/orderListPage
     * 以list形式获取所有订单（带分页参数）
     */
    @ResponseBody
    @GetMapping("/orderListPage")
    public ApiResult<Page<OrderInfo>> orderListPage(@RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
                                        @RequestParam(value = "size", defaultValue = "10") Integer pageSize) {
        Page<OrderInfo> list = orderService.getList(new Page<>(pageNo, pageSize));
        return ApiResult.success(list);
    }

}
